<script setup>
import {
  defineComponent,
  reactive,
  toRefs,
  ref,
  computed,
  nextTick,
  watch,
  h,
  onMounted,
} from "vue";

// 每一个卡片组件
import GraphicTextCardItem from "./helpers/GraphicTextCardItem.vue";
// 工具函数
import { tool } from "@/common/utils/richTextProcessing.js";

import  GTC_tools from "@/views/shotstack/utils/helper.js";

import {
  DeleteOutlined,
  EditOutlined,
  UploadOutlined,
  DownloadOutlined,
  DownOutlined,
} from "@ant-design/icons-vue";
import { useRouter, useRoute } from "vue-router";
import { message } from "ant-design-vue";

// 图片模板弹窗
import GraphicImgTemplateDialog from './helpers/GraphicImgTemplateDialog.vue'
const GraphicImgTemplateDialogRef = ref()

// 文案编辑弹窗
import GraphicTextEditDrawer from './GraphicTextEditDrawer.vue'
const GraphicTextEditDrawerRef = ref()

// 素材库
import ChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/chooseMaterial.vue";
import request from "@/common/utils/request";
import _ from "lodash";
// 仓库
import { useStore } from "vuex";
// 仓库
const store = useStore();
const route = useRoute();

const emit = defineEmits([
  "updateName",
  "openAicreateImg:data",
  "deletItemData"
]);

const props = defineProps({
  itemData: {
    type: Object,
    default() {
      return {};
    },
  },
  explableData: {
    type: Array,
  },
  targetIndex: {
    type: Number,
  },
  /** 文生图需要的模型id
   *  modelId
      feature_id,
   */
  ai_requestData: {
    type: Object,
    default() {
      return {};
    },
  },
});

const state = reactive({
  isGobackModal: false,
  iptShow: false, //控制镜头组输入框显示
  // materialName: "", //镜头组名称
  showImage: false, //控制查看图片弹窗显示隐藏
  materiallibrary: null, //新素材库弹窗实例
  materialVisible: false, //控制上传文件弹窗显示隐藏
  currentFolder: {}, //上传素材类型
  materiallibraryShow: false, //控制老系统素材库弹窗显示隐藏
  viewImgInfo: null, //弹窗图片信息
  // visible: false, // 智能生图下拉菜单开关
  visibleType: "", // select 为选择增加或者编辑场景 add 为增加场景 edit 为编辑场景
  textareaText: "",
  newChooseMaterialShow: false,
  // 当前高亮的ai图片
  // selectAi_img: "",
});

// 用于回显的文件夹项目层级id
const folder_ids = ref({
  // 默认打开的项目id
  merchant_library_id: null,
  // 默认打开的文件夹id
  merchant_folder_statck_id: null,
  group_id: null
})

// 标题
const isName = computed({
  get() {
    return props.itemData.name;
  },
  set(val) {
    emit("updateName", val);
  },
});


// 仓库中的图文剪辑数据 
const GraphicTextMixCutData = computed(() => {
    return store.state.GraphicTextMixCut.GraphicTextMixCutData;
});

const detailDataInfo = computed(() => {
  return JSON.parse(JSON.stringify(props.explableData));
});
// 获取组件列表实例
const itemCardList = ref(null);

// 计算属性 获取展示的项和折叠的项 images
const showListCart = computed(() => {
  const itemCardListWidth = itemCardList.value?.offsetWidth;
  const list = props.itemData.images;

  if (!itemCardListWidth || !props.itemData.images) {
    return {
      foldArr: [],
      showContent: [],
      itemCardListWidth,
    };
  } else {
    // 计算容器能够完全展示多少个卡片
    const cardWidth = 90; // 假设卡片宽度固定为90px
    const maxVisibleCards =
      Math.floor((itemCardListWidth - 124) / cardWidth) - 1;
    // 分割数组，前maxVisibleCards个元素用于展示，剩下的放在foldArr中
    const showContent = list.slice(0, maxVisibleCards);
    const foldArr = list.slice(maxVisibleCards);
    
    // foldArr.push(showContent[showContent.length - 1]);
    const data = { showContent, foldArr, itemCardListWidth };
    return data;
  }
});


// 素材库导入
const materialUploadHandle = () => {
  state.materiallibraryShow = true;
};
// 每个标题的change事件, 提示用户不等你超过20个字符
const inputChange = (e) => {
  nextTick(() => {
    isName.value.length > 20 &&
      (() => {
        // 阻止输入的额外字符
        isName.value = isName.value.slice(0, 20);
        message.warning("镜头组名称长度不能超过 20");
      })();
  });
};
// 输入框获取焦点, 存储旧的值
const oldVal = ref("");
const iptFocus = (ev) => {
  oldVal.value = isName.value;
};
const iptRef = ref(null);
const inputEdit = () => {
  state.iptShow = true;
  nextTick(() => {
    iptRef.value && iptRef.value.focus();
  });
};
// 输入框失去焦点, 判断新值是否符合规则
const iptBlur = (ev) => {
  if (isName.value.trim().length <= 0) {
    isName.value = oldVal.value;
    // emit('updateName', oldVal.value)
    message.warning("镜头组名称不能为空!");
  } else {
    // emit('updateName', isName.value)
  }
  state.iptShow = false;
};

// 预览图片或视频
const videoDialog = ref(null);
const toView = (data) => {
  console.log(data);
  // 查看图片
    state.viewImgInfo = data;
    state.showImage = true;
};

// 删除图片
const delItem = (item) => {
  console.log(item, "item-------");
  let list = JSON.parse(
    JSON.stringify(
      GraphicTextMixCutData.value.resource_data[props.targetIndex]?.images
    )
  );

  const index = list.findIndex((ele) => ele.id == item.id);
  if (index !== -1) {
    GraphicTextMixCutData.value.resource_data[props.targetIndex]?.images?.splice(
      index,
      1
    );
  }

  // 如果没有数据, 用示例素材替换
  if (
    detailDataInfo.value &&
    detailDataInfo.value?.[props.targetIndex] &&
    GraphicTextMixCutData.value.resource_data[props.targetIndex].images.length <= 0
  ) {
    if (detailDataInfo.value) {
      let exchangeData =
        detailDataInfo.value[props.targetIndex] &&
        detailDataInfo.value[props.targetIndex].images.filter(
          (item) => item.system_default == 1
        );
      GraphicTextMixCutData.value.resource_data[props.targetIndex].images =
        exchangeData;
    }
  }
  //  更新仓库
  store.commit('GraphicTextMixCut/INIT_GRAPHICTEXT_DATA', GraphicTextMixCutData.value)
  setTimeout(() => {
    console.log(GraphicTextMixCutData.value.resource_data, "更新仓库---删除了图片或视频");
  }, 500);
  message.success("删除成功");
};

// 素材导入回调
const closeChooseMaterial = (data, key) => {
  if (!data) {
    state.materiallibraryShow = false; //关闭弹窗
    return;
  }
  console.log(data, '选择的素材');
  
  console.log(key, "keykeykeyyeyeyeyeye");
  
  // state.newChooseMaterialShow = false; //关闭弹窗
  state.materiallibraryShow = false; //关闭弹窗

  if (props.itemData.images.length >= 50) {
    return message.warning("单视频组最多可添加50个素材");
  } else if (
    data.length >= 1 &&
    props.itemData.images.length + data.length > 50
  ) {
    message.warning("单视频组最多可添加50个素材, 已自动去除多余素材");
    const sliceNum = 50 - props.itemData.images.length; // 计算可以添加的素材数量
    const existingIds = props.itemData.images.map((item) => item.id);
    // 遍历data，只添加未在existingIds中出现的素材
    let finds = data.filter(
      (ele) => !existingIds.some((i) => i == `${ele[key]}_${ele.id}`)
    );
    finds = finds.slice(0, sliceNum);
    data = finds;
  }

  console.log(data,'选择的素材');
  
  let filterList = data?.map((item, index) => {
    return {
      // 文件
      material_url: item.material_url,
      // 文件名称
      material_name: item.material_name,
      // 素材类型
      scene_type: item[key],
      // id
      org_id: item.org_id,
      // 文件时长
      material_duration: item.material_duration,
      // 文件后缀
      material_extension: item.material_extension,
      // 文件大小
      material_size: item.material_size,
      // 素材路径
      material_path: item.material_path,
      // 素材id
      material_id: item.id,
      // 文件路径
      url: item.material_url,
      // 阿里云需要使用的 media_id
      media_id: item?.oss_media_id || "",
      id: item.id,
      width: item?.width,
      height: item?.height
    };
  });
  if (!filterList?.length) return;

  let showMsg = false;
  filterList.forEach((item) => {
    // 去重
    const index = props.itemData.images.findIndex(
      (existingItem) => existingItem.id == item.id
    );
    if (index == -1) {
      props.itemData.images.push({
        ...item,
        material_duration:0,
      });
    } else {
      showMsg = true;
    }
  });

  if (showMsg) message.info("已为您自动去除重复素材");

  // 更新vuex对应的images
  GraphicTextMixCutData.value.resource_data[props.targetIndex].images =
    props.itemData.images.filter((item) => item.system_default !== 1);
  // 更新仓库
  store.commit('GraphicTextMixCut/INIT_GRAPHICTEXT_DATA', GraphicTextMixCutData.value)

  setTimeout(() => {
    console.log(GraphicTextMixCutData.value.resource_data, "更新了仓库中的素材");
  }, 500);
};

// 热门素材导入
const popularMaterialHandle = () => {
};

// 删除镜头组
const deleteGroupHandle = () => {
  if (GraphicTextMixCutData.value.resource_data.length <= 1) {
    message.error("至少保留一个镜头组");
    return
  }

  emit('deletItemData')
  message.success("删除成功");
};

const openAicreateImg = () => {
  emit("openAicreateImg", props.targetIndex);
};

// 重新绘制, 打开ai生图
const repaint = () => {
  emit("openAicreateImg", props.targetIndex);
};

// 素材库组件 emit 退出时的项目和文件夹位置
const storeMemory = (data) => {
  console.log(data, '退出时的项目和文件夹位置');
  Object.assign(folder_ids.value, data)
}

// 配置图片模板
const openImgTemplate = () => {
  GraphicImgTemplateDialogRef.value?.showModal({index: props.targetIndex})
}

// 打开文案编辑
const openGraphicTextEditDrawer = () => {
  GraphicTextEditDrawerRef.value?.showDrawer({index: props.targetIndex})
}
</script>

<template>
  <!-- class="item-card" -->
  <div class="content_box">
    <div class="item_card_header">
      <!-- 抓手 - 匿名插槽 -->
      <slot name="default"></slot>
      <!-- {{ itemData.images }} -->
      <!-- 头部输入框 -->
      <div class="header_box">
        <div class="header_left">
          <div class="header_top">
            <div v-if="!state.iptShow">
              <span>{{ isName }}</span>
              <a-tooltip>
                <template #title>编辑</template>
                <edit-outlined @click="inputEdit" />
              </a-tooltip>
            </div>
            <div v-else>
              <!-- :maxlength="20" -->
              <a-input v-model:value="isName" @pressEnter="state.iptShow = false" @blur="iptBlur($event)"
                @change="inputChange($event)" @focus="iptFocus($event)" ref="iptRef"></a-input>
            </div>
          </div>
          <div class="header_bottom">
            <span style="font-size: 12px">
              素材数量 &nbsp;
              <a-tag style="font-size: 12px; line-height: 12px; padding: 2px">{{props.itemData?.images?.length}}</a-tag>
            </span>
          </div>
        </div>

        <div class="header-right">
          <div class="header-bottom-btngroup">
            <a-popconfirm title="确定删除该镜头组?" ok-text="确定" cancel-text="取消" @confirm="deleteGroupHandle">
              <span v-if="props?.targetIndex != 0" class="delete-btn"><delete-outlined />删除镜头组</span>
            </a-popconfirm>
          </div>
        </div>
      </div>
    </div>

    <!-- 卡片主体部分 -->
    <div class="cart_list_box" ref="itemCardList">
      <!-- 上传的卡片 -->
      <div class="upload_box">
        <div class="upload_desc">
          <div style="font-size: 24px; font-weight: 600">+</div>
          <div>添加素材</div>
        </div>
        <div class="upload_img_mask">
          <!-- <span class="upload_img-local" @click="popularMaterialHandle"><upload-outlined />热门素材</span>
          <span class="line"></span> -->
          <span class="upload_img-origin" @click="materialUploadHandle"><download-outlined />素材库导入</span>
        </div>
      </div>
      <!-- 列表渲染的卡片 -->
      <div v-for="item in showListCart.showContent" :key="item.id">
        <GraphicTextCardItem :item="item" @delItem="delItem" @toView="toView" @repaint="repaint" :viewMore="false"></GraphicTextCardItem>
      </div>

      <!-- 多余的数据只有当切割素材的数量大于1的时候才显示 -->
      <template v-if="showListCart.foldArr.length >= 1">
        <!-- 多余的只有一项, 和普通的卡片没有区别 -->
        <template v-if="showListCart.foldArr.length == 1">
          <GraphicTextCardItem :item="showListCart.foldArr[0]" @delItem="delItem" @toView="toView" @repaint="repaint"></GraphicTextCardItem>
        </template>
        <!-- 多余的有多项, 第一个特殊处理, 其余的项放在折叠面板中 -->
        <template v-else>
          <!-- 第一个特殊处理 -->
          <GraphicTextCardItem :item="showListCart.foldArr[0]" @delItem="delItem" @toView="toView" @repaint="repaint"
            :viewMore="true" :moreList="showListCart.foldArr"></GraphicTextCardItem>
        </template>
      </template>
    </div>

    <!-- 底部按钮 -->
    <div class="item-card-footer">
      <span class="item-card-footer_btn" style="margin-left: 5px" @click="openGraphicTextEditDrawer">
        文案贴纸设置
        <!-- <down-outlined /> -->
      </span>

      <span class="item-card-footer_btn" style="margin-left: 5px" @click="openImgTemplate">
        图片模板
        <!-- <down-outlined /> -->
      </span>

    </div>
    <!-- 查看图片弹窗 -->
    <a-modal width="500px" v-model:visible="state.showImage" :title="state.viewImgInfo?.material_name"
      @ok="state.showImage = false" centered>
      <div style="display: flex; justify-content: center; align-items: center">
        <img style="width: 450px; max-height: 300px; object-fit: contain" :src="state.viewImgInfo?.material_url"
          alt="" />
      </div>
    </a-modal>

    <ChooseMaterial 
    :isClip="false" 
    :multiple="true" 
    :visible="state.materiallibraryShow" 
    :showContent="showListCart.showContent" 
    :targetIndex="props.targetIndex" 
    :folder_ids="folder_ids"
    extension="jpg,png,bpm,webp,jpeg"
    @close="closeChooseMaterial($event, 'material_type')" 
    @openAicreateImg="openAicreateImg"
    @storeMemory="storeMemory" />

    <!-- 图片模板选择弹窗 -->
    <GraphicImgTemplateDialog ref="GraphicImgTemplateDialogRef"></GraphicImgTemplateDialog>

    <!-- 文案编辑弹窗 -->
    <GraphicTextEditDrawer ref="GraphicTextEditDrawerRef"></GraphicTextEditDrawer>
  </div>
</template>

<style lang="less" scoped>
.content_box {
  @cart_bgc: #f1f3f5;

  //卡片的样式
  .material_item {
    // background-color: #000;
  }

  // 头部样式
  .item_card_header {
    color: #737a87;
    background: #fafbfc;
    padding: 20px;
    position: relative;

    .header_box {
      display: flex;
      justify-content: space-between;

      &:hover {
        & .header-right .delete-btn {
          visibility: visible;
          color: var(--ss-primary-6);
        }
      }
    }

    .header_top {
      font-weight: 600;
      line-height: 20px;
    }

    .header_bottom {
      display: flex;
      margin-top: 5px;
      color: var(--color-text-3);
      justify-content: space-between;
      align-items: center;
    }

    // 右侧删除按钮
    .header-right {
      margin-top: 16px;

      .header-bottom-btngroup {
        .delete-btn {
          font-size: 12px;
          margin-right: 10px;
          visibility: hidden;
          cursor: pointer;
        }
      }
    }
  }

  // 列表主体
  .cart_list_box {
    padding: 0 20px;
    display: flex;

    // 添加素材的卡片样式
    .upload_box {
      width: 84px;
      height: 120px;
      border-radius: 5px;
      position: relative;
      margin: 0 5px;

      &:hover {
        & .upload_img_mask {
          opacity: 1;
        }
      }

      .upload_img_mask {
        position: absolute;
        left: 0;
        top: 0;
        width: 84px;
        height: 114px;
        background: #f1f3f5;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        opacity: 0;

        .upload_img-local,
        .upload_img-origin {
          align-items: center;
          justify-content: center;
          display: flex;
          height: 48%;
          font-size: 12px;
        }

        .line {
          height: 1px;
          width: 80%;
          background: #dde2e9;
        }

        & span {
          cursor: pointer;
        }
      }

      // 鼠标触摸之前的描述文本
      .upload_desc {
        background: @cart_bgc;
        width: 84px;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
      }
    }
  }
}

// 底部样式
.item-card-footer {
  margin-top: 10px;
  padding: 20px;
  cursor: pointer;

  :deep(.ss-popover-inner-content) {
    padding: 0;
  }

  .smart_create {
    padding: 6px 12px;

    .smart_create_item {
      width: 100%;
      padding: 2px;
      cursor: pointer;

      &:hover {
        color: var(--ss-primary-5);
      }
    }

    .disable_smart_create_item {
      width: 100%;
      padding: 2px;
      cursor: pointer;
      color: #afafaf;

      &:hover {
        color: #9a9a9a;
      }
    }
  }

  // 智能生图输入提示词
  .smart_create_desc_box {
    width: 650px;
    padding: 12px 0;

    .title {
      padding: 0 12px 8px 12px;
      font-size: 14px;
      border-bottom: 0.5px solid #c7c7c7;
    }

    .desc_content {
      padding: 12px;
      padding-top: 0;
      margin-top: 14px;
    }

    .btn_box {
      display: flex;
      justify-content: flex-end;
      gap: 12px;
      padding: 0 12px;
    }
  }

  // 'margin-left': '5px',
  // display: 'inline-block',
  // 'max-width': '200px',
  // background:  selectAi_img == '' ? '#fafbfd' : '#f6f8fa',
  // padding: '5px',
  // border: '1px solid #dde2e9',
  // 'border-color': selectAi_img == '' ? '#dde2e9' : '#dde2e9',
  // color: selectAi_img == '' ? '#b4b4b4' : '#555555',
  // 'font-size': '12px',
  // 'border-radius': '5px',
  // overflow: 'hidden',
  // 'text-overflow': 'ellipsis',
  // 'white-space': 'nowrap',
  // cursor: selectAi_img == '' && 'not-allowed'

  .item-card-footer_btn {
    display: inline-block;
    max-width: 200px;
    background: #f6f8fa;
    padding: 5px;
    border: 1px solid #dde2e9;
    color: #555555;
    font-size: 12px;
    border-radius: 5px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  // 禁用的样式
  .disable_card_footer_btn {
    color: #b4b4b4;
    background-color: #fafbfd;
    border-color: #dde2e9;
    cursor: not-allowed;
  }
}

.item_card_img:hover .upload_img {
  display: none;
}

.item_card_img:hover .upload_img_mask {
  visibility: visible;
}

.upload_img-local:hover,
.upload_img-origin:hover {
  color: #2878ff;
}
</style>
